<template>
  <div class="main-container">
    <!-- 条件搜索 -->
    <Condition>
      <div class="condition-item condition-item-5">
        <span class="condition-label">用户名称</span>
        <el-input 
          class="condition-input" 
          v-model="conditionForm.userName" 
          placeholder="请输入用户名称" 

          @change="getList" 
        />
      </div>
      <div class="condition-item condition-item-5">
        <span class="condition-label">用户状态</span>
        <el-select
          class="condition-input"
          v-model="conditionForm.status"
          placeholder="请选择用户状态"
          clearable
          @change="getList"
        >
          <el-option v-for="(item, index) in userStatus" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <!-- <div class="condition-item item-3">
        <span class="condition-label">用户类型</span>
        <el-select
          class="condition-input"
          v-model="conditionForm.userType"
          placeholder="请选择用户类型"
          clearable
          @change="getList"
        >
          <el-option v-for="(item, index) in userTypes" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </div> -->
    </Condition>
    <!-- 底下表格部分 -->
    <div class="data-show">
      <!-- 头部操作按钮部分 -->
      <div class="data-actions">
        <span class="aniTxtBtn action" @click="linkToCreate">新增用户</span>
      </div>
      <!-- 表格 -->
      <div class="data-table">
        <el-table border :data="datas" stripe show-header>
          <el-table-column label="序号" align="center" type="index" width="100" />
          <el-table-column label="用户名" align="center" prop="userName" />
          <el-table-column label="昵称" align="center" prop="nickName" />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="{row}">
              {{ getShow(row.status, 'value', userStatus, 'label') }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" show-overflow-tooltip prop="createTime" />
          <el-table-column label="操作" align="center" width="280" fit>
            <template #default="scope">
              <div class="table-actions">
                <button class="aniTxtBtn blue" @click="linkToEdit(scope.row)">编辑</button>
                <button class="aniTxtBtn" :class="{red: scope.row.status == '0', 'main-color': scope.row.status != '0'}" @click="stop(scope.row)">
                  {{ scope.row.status == '0' ? '停用' : '启用' }}
                </button>
                <button class="aniTxtBtn red" @click="del(scope.row)">删除</button>
              </div>
            </template>
          </el-table-column>
          <!-- 没有数据时显示 -->
          <template #empty>
            <i class="iconfont icon-wushuju1 data-empty-icon"></i>
            <h3 class="data-empty">暂无数据</h3>
          </template>
        </el-table>
      </div>
      <Pagination
        v-show="conditionForm.totalRow > 0" 
        :total="conditionForm.totalRow"
        v-model:page="conditionForm.pageNumber"
        v-model:limit="conditionForm.pageSize"
        @pagination="pageChange" 
      />
    </div>
  </div>
</template>
<script setup>
import Condition from '@/components/common/Condition.vue';
import Pagination from '@/components/common/Pagination.vue';
import * as userApi from '@/api/user';
import { ref, computed, onActivated } from 'vue';
import { api } from '@/utils/status';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';


// ============> data
const router = useRouter();
const userStatus = ref(api.user.status);
const userTypes = ref(api.user.types);
// 搜索条件表单项
const conditionForm = ref({
  flag: false,
  loading: false,
  userName: '',
  saveUserName: '',
  status: null,
  saveStatus: null,
  // userType: null,
  // saveUserType: null,
  // 页条数
  pageSize: 10,
  // 当前页
  pageNumber: 1,
  // 总条数
  totalRow: 0,
  // 总页数
  totalPage: 0
});
const datas = ref([]);

// ============> computed
const getShow = computed(() => {
  return function (v, k, arr, returnKey) {
    let obj = arr.find((item) => item[k] == v);
    let res = obj ? obj[returnKey] : "--";
    return res;
  };
});

// ============> methods
function linkToCreate(){
  router.push({ name: 'userCreate' });
}
// 重置上方的搜索条件
function resetCondition(){
  conditionForm.value.userName = conditionForm.value.userName != conditionForm.value.saveUserName ? conditionForm.value.saveUserName : conditionForm.value.userName;
  conditionForm.value.status = conditionForm.value.status != conditionForm.value.saveStatus ? conditionForm.value.saveStatus : conditionForm.value.status;
}
// 设置上方的搜索条件
function setCondition(){
  conditionForm.value.saveUserName = conditionForm.value.userName;
  conditionForm.value.saveStatus = conditionForm.value.status;
}
function getList(){
  if (conditionForm.value.flag){
    resetCondition();
    return;
  }
  conditionForm.value.loading = true;
  const { userName,status, pageSize, pageNumber } = conditionForm.value;
  userApi.getUserList({ userName, status, pageSize, pageNumber})
    .then(res => {
      datas.value = res.records && Array.isArray(res.records) ? res.records : [];
      initDatas();
      setCondition();
      conditionForm.value.pageNumber = +res.pageNumber;
      conditionForm.value.pageSize = +res.pageSize;
      conditionForm.value.totalRow = +res.totalRow;
      conditionForm.value.totalPage = +res.totalPage;
      conditionForm.value.loading= false;
      conditionForm.value.flag = false;
    })
    .catch(err => {
      conditionForm.value.loading = false;
      conditionForm.value.flag = false;
      console.log(err)
      resetCondition();
    })
}
function initDatas(){
  if (Array.isArray(datas.value) && datas.value.length > 0){
    datas.value.forEach(item => {
      item.stopFlag = false;
      item.delFlag = false;
    })
  }
}
// 分页触发事件
function pageChange(e){
  // { page, limit }
  conditionForm.value.pageSize = e.limit;
  conditionForm.value.pageNumber = e.page;
  getList();
}
function stop(item){
  if (item.stopFlag){
    ElMessage.warning('当前正在切换用户状态，请稍后重试');
    return;
  }
  ElMessageBox.confirm('您是否确认切换该用户状态？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(() => {
      item.stopFlag = true;
      let user = Object.assign({}, item);
      user.status = user.status == '0' ? '1' : '0';
      userApi.setStatus(user)
        .then(res => {
          ElMessage.success('修改用户状态成功！');
          item.stopFlag = false;
          getList();
        })
        .catch(err => {
          console.log(err)
          item.stopFlag = false;
          // let msg = err.msg || err.message || '修改用户状态失败，请稍后重试或联系管理员';
          // ElMessage.error(msg);
        })
    })
    .catch(() => {})
}
function del(item){
  if (item.delFlag){
    ElMessage.warning('当前正在删除该用户，请稍后');
    return;
  }
  ElMessageBox.confirm('您是否确认删除该用户？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(() => {
      item.delFlag = true;
      userApi.delUser({userId: item.userId})
        .then(res => {
          ElMessage.success('删除用户成功');
          getList();
        })
        .finally(() => {
          item.delFlag = false;
        })
    })
    .catch(() => {})
}
function linkToEdit(item){
  router.push({ name: 'userCreate', query: { id: item.userId} });
}

// onMounted(() => {
//   getList();
// });

onActivated(() => {
  getList();
});

</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.table-actions {
  display: flex;
  align-items: center;
  justify-content: space-around;
  @include wh-100;
  .action {
    width: 80px;
  }
}
.green {
  color: var(--color-green);
}
.red {
  color: var(--color-red);
  @include red-text-shadow;
}
.blue {
  color: var(--color-text-hover);
  @include blue-text-shadow;
}
.main-color {
  color: var(--color-main);
  @include main-text-shadow;
}
.condition-item-5 {
  width: 46%;
}
</style>